import { transformRequest, transformResponse, catchError, errorTip } from './common';
import { beforeSend, afterSend } from './hook';
import axios from 'axios';
import Vue from 'vue';
// axios封装
Vue.prototype.$http = axios;
const instance = axios.create({
  timeout: 120 * 1000,
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: false, // 默认值
  baseURL: process.env.VUE_APP_API,
});

instance.interceptors.request.use(transformRequest, Promise.reject);

async function axiosCall(options) {
  try {
    beforeSend(options);
    return await instance(options)
      .catch(catchError)
      .then(transformResponse);
  } catch (err) {
    errorTip(err, options);
    throw err;
  } finally {
    afterSend(options);
  }
}

export default {
  get: async function(url, options) {
    options.method = 'GET';
    options.url = url;
    // 不使用mock数据时,发送get请求带上请求参数
    if (process.env.VUE_APP_HAS_MOCK === 'false') {
      options.params = options.query;
    }
    return axiosCall(options);
  },
  post: async function(url, options) {
    options.method = 'POST';
    options.url = url;
    options.data = options.payload || {};
    return axiosCall(options);
  },
  // FormData格式
  postForm: async function(url, options) {
    options.method = 'POST';
    const formdata = new FormData();
    const data = options.payload || {};
    for (const key in data) {
      if (Object.hasOwnProperty.call(data, key)) {
        formdata.append(key, data[key]);
      }
    }
    options.headers = Object.assign({}, options.headers || {}, {
      'Content-Type': 'multipart/form-data',
    });
    options.url = url;
    options.data = formdata;
    return axiosCall(options);
  },
  postBlob: async function(url, options) {
    options.method = 'POST';
    options.url = url;
    options.data = options.payload;
    options.responseType = 'blob';
    return axiosCall(options);
  },
};
